from fastapi import APIRouter, Request, Body
from pydantic import BaseModel
from typing import Optional
from decimal import Decimal
from finance.python.middleware.auth import token_required
from finance.python.middleware.logging import log_required
from finance.python.services import bill_service

# 创建路由器
bill_router = APIRouter(
    prefix="/api",
    tags=["bill"]
)


# 获取账单列表
@bill_router.get("/get_bills", summary="查询账单")
@token_required
@log_required
async def get_bills(
    request: Request,
    bill_type: Optional[str] = None,
    type: Optional[int] = None,
    payment_status: Optional[int] = None,
    payment_method: Optional[str] = None,
    current_page: Optional[int] = None,
    page_size: Optional[int] = None,
):
    """
    获取账单列表
    :param bill_type: 账单类型
    :param type: 支付类型
    :param payment_status: 支付状态
    :param payment_method: 支付方式
    :param current_page: 当前页码
    :param page_size: 每页条数
    """
    user_id = request.state.user_id
    return await bill_service.get_bills(
        user_id,
        bill_type,
        type,
        payment_status,
        payment_method,
        current_page,
        page_size
    )


class BillRequest(BaseModel):
    bill_type: str
    amount: Decimal
    type: int
    payment_status: Optional[int] = None
    payment_method: Optional[str] = None
    due_date: Optional[str] = None
    description: Optional[str] = None
    bill_id: Optional[int] = None


@bill_router.post("/add_bill", summary="添加账单")
@token_required
@log_required
async def add_bill(request: Request, add_bill_data: BillRequest = Body(...)):
    """
    添加账单
    :param request: 请求对象
    :param add_bill_data: 账单数据
    """
    user_id = request.state.user_id
    return await bill_service.add_bill(
        user_id,
        add_bill_data.bill_type,
        add_bill_data.amount,
        add_bill_data.type,
        add_bill_data.payment_status,
        add_bill_data.payment_method,
        add_bill_data.due_date,
        add_bill_data.description
    )


@bill_router.delete("/delete_bill", summary="删除账单")
@token_required
@log_required
async def delete_bill(request: Request, bill_id = Body(...)):
    """
    删除账单
    :param request: 请求对象
    :param bill_id: 账单ID
    """
    user_id = request.state.user_id
    return await bill_service.delete_bill(user_id, bill_id['bill_id'])


@bill_router.put('/update_bill', summary="更新账单")
@token_required
@log_required
async def update_bill(request: Request, update_bill_data: BillRequest = Body(...)):
    """
    更新账单
    :param request: 请求对象
    :param update_bill_data: 账单数据
    """
    user_id = request.state.user_id
    return await bill_service.update_bill(
        user_id,
        update_bill_data.bill_id,
        update_bill_data.bill_type,
        update_bill_data.amount,
        update_bill_data.type,
        update_bill_data.payment_status,
        update_bill_data.payment_method,
        update_bill_data.due_date,
        update_bill_data.description
    )
